var myreg = /^([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+@([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+\.[a-zA-Z]{2,3}$/;
function check(name, email, content) {
    var flag = true;
    var pos1 = document.getElementsByName('name')[0];
    var pos2 = document.getElementsByName('email')[0];
    var pos3 = document.getElementsByName('content')[0];
    var err = document.querySelectorAll('.err');
    if (name.length == 0) {
        flag = false;
        err[0].innerHTML = '名字 必须填写';
    } else {
        err[0].innerHTML = '';
    }
    if (email.length == 0) {
        flag = false;
        err[1].innerHTML = '邮箱 必须填写';
    } else if (!myreg.test(email)) {
        flag = false;
        err[1].innerHTML = '邮箱 格式不对';
    } else {
        err[1].innerHTML = '';
    }
    if (content.length == 0) {
        flag = false;
        err[2].innerHTML = '内容 必须填写';
    } else {
        err[2].innerHTML = '';
    }
    return flag;
}

let sub = document.getElementById('sub')
sub.addEventListener('click', async () => {
    let name = (<HTMLInputElement>document.getElementsByName('name')[0]).value
    let email = ( <HTMLInputElement>document.getElementsByName('email')[0]).value
    let time = (<HTMLInputElement> document.getElementsByName('time')[0]).value
    let content = ( <HTMLInputElement>document.getElementsByName('content')[0]).value
    let tip =  (<HTMLInputElement>document.getElementsByName('tips')[0]).value
    if(!tip){tip=" "}
    if (check(name, email, content)) {
        let res = await fetch('http://127.0.0.1:3280/api/add', {
            method: 'POST',
            body: JSON.stringify({
                name: name,
                email: email,
                time: time,
                content: content,
                tip: tip
            }),
            headers: {}
        })
        let json = await res.json()
        let id=json.id
        localStorage.setItem("__id__",id)
        window.location.href="../html/put_done.html"
    }
})